package com.test.webchat.WebSocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.webchat.Component.OnlineUserManager;
import com.test.webchat.Pojo.Model.Friend;
import com.test.webchat.Pojo.Model.Message;
import com.test.webchat.Pojo.Model.MessageRequest;
import com.test.webchat.Pojo.Response.MessageResponse;
import com.test.webchat.Pojo.Response.UserInfoSimple;
import com.test.webchat.Service.MessageService;
import com.test.webchat.Service.UserService;
import com.test.webchat.Utils.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
@Slf4j
public class WebSocket extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Integer userId = WebSocketUtil.getUserId(session);
        if (userId != null) {
            onlineUserManager.online(userId, session);
            log.info("建立连接");
        } else {
            log.info("连接的userId为null！！！");
        }

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[WebSocketAPI] 收到消息!" + message.toString());
        Integer userId = WebSocketUtil.getUserId(session);
        if (userId == null) {
            System.out.println("[WebSocketAPI] user == null! 未登录用户, 无法进行消息转发");
            return;
        }
        MessageRequest messageRequest = objectMapper.readValue(message.getPayload(), MessageRequest.class);
        if (messageRequest.getType().equals("message")) {
            // 就进行消息转发
            transferMessage(userId, messageRequest);
        } else {
            System.out.println("[WebSocketAPI] req.type 有误! " + message.getPayload());
        }
    }

    private void transferMessage(Integer userId, MessageRequest messageRequest) throws IOException {
        // 设置响应对象
        MessageResponse messageResponse = new MessageResponse();
        UserInfoSimple userInfo = userService.getUserInfo(userId);

        messageResponse.setFromId(userId);
        messageResponse.setFromName(userInfo.getUserName());
        messageResponse.setSessionId(messageRequest.getSessionId());
        messageResponse.setContent(messageRequest.getContent());
        String response = objectMapper.writeValueAsString(messageResponse);

        List<Friend> friendList = userService.getFriendList(userId);
        Friend friend = new Friend(userId, userInfo.getUserName());
        friendList.add(friend);

        // 给会话中的每个用户都发送消息
        for (Friend f : friendList) {
            WebSocketSession webSocketSession = onlineUserManager.getwebSocketSession(f.getFriendId());
            if (webSocketSession == null) {
                // 如果该用户未在线, 则不发送.
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(response));
        }

        // 将消息持久化
        Message message = new Message();
        message.setFromId(userId);
        message.setFromName(userInfo.getUserName());
        message.setSessionId(messageRequest.getSessionId());
        message.setContent(messageRequest.getContent());
        messageService.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        Integer userId = WebSocketUtil.getUserId(session);
        if (userId != null) {
            onlineUserManager.online(userId, session);
            log.info("发生异常");
        } else {
            log.info("连接的userId为null！！！");
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Integer userId = WebSocketUtil.getUserId(session);
        if (userId != null) {
            onlineUserManager.online(userId, session);
            log.info("关闭连接");
        } else {
            log.info("连接的userId为null！！！");
        }
    }
}
